跳到主要内容

JZ16 合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode result = new ListNode(0);
ListNode temp = result;
while(list1 != null || list2 != null) {
// list1 == null 那 list2 肯定不为 null
// 这两个判断主要是用于另一个 list 为空时的收尾工作
if (list1 == null) {
temp.next = list2;
list2 = list2.next;
temp = temp.next;
continue;
}

if (list2 == null) {
temp.next = list1;
list1 = list1.next;
temp = temp.next;
continue;
}

if (list1.val > list2.val) {
temp.next = list2;
list2 = list2.next;
temp = temp.next;
} else {
temp.next = list1;
list1 = list1.next;
temp = temp.next;
}

}

return result.next;
}
}